<template>
  <div class="reset-password-container">
    <el-card class="reset-password-card">
      <h2>重置密码</h2>
      <el-form 
        :model="resetForm" 
        :rules="rules" 
        ref="resetFormRef"
      >
        <!-- API错误信息 -->
        <el-input
          v-if="apiError"
          v-model="apiError"
          type="textarea"
          :rows="5"
          readonly
          class="error-textarea"
        />

        <el-form-item prop="email">
          <el-input 
            v-model="resetForm.email" 
            placeholder="邮箱" 
            :disabled="formLoading"
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
            <template #append>
              <el-button 
                @click="handleSendCode" 
                :disabled="formLoading || codeSending || countdown > 0"
              >
                {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="code">
          <el-input 
            v-model="resetForm.code" 
            placeholder="验证码" 
            :disabled="formLoading"
          >
            <template #prefix>
              <el-icon><Key /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="new_password">
          <el-input 
            v-model="resetForm.new_password" 
            placeholder="新密码" 
            type="password"
            :disabled="formLoading"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleResetPassword" 
            :loading="formLoading"
            style="width: 100%"
          >
            重置密码
          </el-button>
        </el-form-item>

        <div class="login-link">
          想起密码了？<router-link to="/login">立即登录</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Lock, Message, Key } from '@element-plus/icons-vue'
import { resetPassword, requestResetPassword } from '@/api/user'

const router = useRouter()
const resetFormRef = ref(null)
const formLoading = ref(false)
const codeSending = ref(false)
const countdown = ref(0)
const apiError = ref('')

const resetForm = reactive({
  email: '',
  code: '',
  new_password: ''
})

const rules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为6位', trigger: 'blur' }
  ],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: 'blur' }
  ]
}

const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const handleSendCode = async () => {
  try {
    await resetFormRef.value.validateField('email')
    codeSending.value = true
    apiError.value = ''
    
    await requestResetPassword({ email: resetForm.email })
    ElMessage.success('验证码已发送到您的邮箱')
    startCountdown()
  } catch (error) {
    apiError.value = JSON.stringify(error.response?.data || error.message, null, 2)
  } finally {
    codeSending.value = false
  }
}

const handleResetPassword = async () => {
  if (formLoading.value) return
  
  try {
    apiError.value = ''  // 清除之前的错误信息
    await resetFormRef.value.validate()
    formLoading.value = true
    await resetPassword(resetForm)
    ElMessage.success('密码重置成功')
    router.push('/login')
  } catch (error) {
    apiError.value = JSON.stringify(error.response?.data || error.message, null, 2)
  } finally {
    formLoading.value = false
  }
}
</script>

<style scoped>
.reset-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
}

.reset-password-card {
  width: 100%;
  max-width: 400px;
}

.reset-password-card h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #303133;
}

.login-link {
  text-align: center;
  margin-top: 16px;
  font-size: 14px;
}

.login-link a {
  color: var(--el-color-primary);
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}

.error-textarea {
  margin-bottom: 16px;
}

:deep(.error-textarea .el-textarea__inner) {
  color: var(--el-color-danger);
  font-family: monospace;
}
</style>
